import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Layout from '@/layout'
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.userId) {
        const {
          roles: { menus }
        } = await store.dispatch('user/getInfo', store.getters.token)
        const routes = await store.dispatch(
          'permission/filterRoutes',
          menus
        )
        router.addRoutes([
          ...routes,
          { path: '*', redirect: '/404', hidden: true },
          { path: '/setting',
            meta: 'settings',
            component: Layout,
            children: [
              {
                path: '',
                component: () => import('@/views/setting'),
                meta: { title: '公司设置', icon: 'setting' }
              }
            ] }
        ])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.some(item => item === to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(function() {
  NProgress.done() // 关闭进度条
})
